# coding=utf8
__author__ = 'lijian'
import protocol.term.ctrl as ctrl
import lamp
import logging
import time

from utils import byteUtil

_updateStateKey = (0x60, 0x61, 0x62, 0x63)


def response_handler(packet):
    if packet.ctrl == ctrl.UNI_CAST or packet.ctrl == ctrl.GRP_CAST \
            or packet.ctrl == ctrl.BROADCAST:
        uid = list(packet.uid)
        uid[0] = 0
        term = lamp.manager.findTremByUID(uid)
        if not term:
            return

        action = packet.dataRegion[2]

        if _updateStateKey.count(action) > 0:
            updateStatus(packet, term)
        else:
            updateDetail(packet, term)


def updateStatus(packet, term):
    data = packet.dataRegion[3:]
    offset = 0
    for i in range(1, 3):
        state = data[offset]
        offset += 1
        level = data[offset]
        offset += 1

        holder = term.findHolderByLine(i)
        if holder:
            logging.debug("update %r status,state:%d,level:%d" % (holder.uid, state, level))

            holder.level = level


def updateDetail(packet, term):
    data = packet.dataRegion[3:]
    offset = 0

    curTime = time.localtime(time.time())

    for i in range(1, 3):
        state = data[offset]
        offset += 1
        level = data[offset]
        offset += 1
        v = byteUtil.decodeShortBigEndian(data[offset:]) / 100.0
        offset += 2
        a = byteUtil.decodeShortBigEndian(data[offset:]) / 100.0
        offset += 2
        w = byteUtil.decodeShortBigEndian(data[offset:])
        offset += 2
        pf = byteUtil.decodeShortBigEndian(data[offset:]) / 100.0
        offset += 2
        ws = byteUtil.decodeIntBigEndian(data[offset:])
        offset += 4
        onTime = byteUtil.decodeIntBigEndian(data[offset:])
        offset += 4

        alarm = data[offset]
        offset += 1

        # 早上9点到晚上20点之间，乎略所有报警
        # if curTime.tm_hour > 9 and curTime.tm_hour < 20:
        #     alarm = 0

        holder = term.findHolderByLine(i)
        if holder:
            logging.debug("update %r detail,state:%d,level:%d" % (holder.uid, state, level))
            holder.level = level

            holder.v = v
            holder.a = a
            holder.w = w
            holder.pf = pf
            holder.ws = ws

            holder.alarmStatue = alarm
